package com.yequan.springmvc.handlermapping;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.yequan.springframework.beandefinition.BeanDefinition;
import com.yequan.springframework.factory.BeanFactory;
import com.yequan.springframework.factory.BeanFactoryAware;
import com.yequan.springframework.factory.DefaultListableBeanFactory;
import com.yequan.springmvc.handlermapping.iface.HandlerMapping;

/**
 * 该处理器映射器，主要是通过bean标签的name值来存储url，和bean标签的class对应的处理器类建立映射
 * 
 * @author 灭霸詹
 *
 */
public class BeanNameUrlHandlerMapping implements HandlerMapping, BeanFactoryAware {

	private DefaultListableBeanFactory beanFactory;
	/**
	 * 存储url和处理器的映射关系
	 */
	private Map<String, Object> urlHandlerMap = new HashMap<String, Object>();

	/**
	 * 初始化方法
	 */
	public void init() {
		// 完成url和处理器的映射关系的建立
		// 获取bean容器，从bean容器中获取BeanDefinition集合
		Map<String, BeanDefinition> beanDefinitions = beanFactory.getBeanDefinitions();
		// 遍历BeanDefinition，针对每个BeanDefinition，取出name值
		for (String beanName : beanDefinitions.keySet()) {
			// 判断name值是否是以/开头的，如果是，则将该BeanDefinition的name和className加入到urlHandlerMap集合
			if (beanName.startsWith("/")) {
				// 建立url和处理器bean的映射关系
				urlHandlerMap.put(beanName, beanFactory.getBean(beanName));
			}
		}
	}

	@Override
	public Object getHandler(HttpServletRequest request) {
		String url = request.getRequestURI();
		return urlHandlerMap.get(url);
	}

	@Override
	public void setBeanFacoty(BeanFactory beanFactory) {
		this.beanFactory = (DefaultListableBeanFactory) beanFactory;
	}

}
